package com.ftqh.security.oauth2.provider.client;

import com.ftqh.core.jpa.service.BaseServiceImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2017/1/5
 * \* Time: 18:36
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class OAuth2ClientDetailsService extends BaseServiceImpl<OAuth2ClientDetails, String, OAuth2ClientDetailsRepository>
        implements ClientDetailsService, ClientRegistrationService {
    private static final Log logger = LogFactory.getLog(JdbcClientDetailsService.class);
    private static RandomValueStringGenerator defaultClientSecretGenerator = new RandomValueStringGenerator(32);

    /*@Autowired
    private BCryptPasswordEncoder passwordEncoder;*/
    private PasswordEncoder passwordEncoder = NoOpPasswordEncoder.getInstance();

    private JsonMapper mapper = createJsonMapper();

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        if(!repository.exists(clientId)){
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }
        return repository.findOne(clientId);
    }

    public void addOAuth2ClientDetails(OAuth2ClientDetails clientDetails) throws ClientAlreadyExistsException {
        try {
            if(clientDetails.getClientSecret()==null ) {
                clientDetails.setClientSecret(defaultClientSecretGenerator.generate());
            }
            clientDetails.setClientSecret(passwordEncoder.encode(clientDetails.getClientSecret()));
            repository.save(clientDetails);
        } catch (DuplicateKeyException e) {
            throw new ClientAlreadyExistsException("Client already exists: " + clientDetails.getClientId(), e);
        }
    }
    @Deprecated
    @Override
    public void addClientDetails(ClientDetails clientDetails) throws ClientAlreadyExistsException {
        if(null == loadClientByClientId(clientDetails.getClientId())){
            OAuth2ClientDetails oAuth2ClientDetails = this.getOauth2ClientDetailsForCreate(clientDetails);
            repository.save(oAuth2ClientDetails);
        }else{
            throw new ClientAlreadyExistsException("Client already exists: " + clientDetails.getClientId());
        }
    }

    @Override
    public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException {
        if(repository.exists(clientDetails.getClientId())){
            OAuth2ClientDetails oAuth2ClientDetails = this.getOAuth2ClientDetailsForUpdate(clientDetails);
            repository.update(oAuth2ClientDetails);
        }else{
            throw new NoSuchClientException("No client found with id = " + clientDetails.getClientId());
        }
    }

    @Override
    public void updateClientSecret(String clientId, String secret) throws NoSuchClientException {
        int count = repository.updateClientSecret(clientId, secret);
        if (count != 1) {
            throw new NoSuchClientException("No client found with id = " + clientId);
        }
    }

    @Override
    public void removeClientDetails(String clientId) throws NoSuchClientException {
        repository.delete(clientId);
    }

    public List<OAuth2ClientDetails> listOAuth2ClientDetails() {
        return repository.findAll();
    }
    @Override
    public List<ClientDetails> listClientDetails() {
        return null;
    }

    private OAuth2ClientDetails getOAuth2ClientDetailsForUpdate(ClientDetails clientDetails){
        OAuth2ClientDetails oAuth2ClientDetails = repository.findOne(clientDetails.getClientId());
        String json = null;
        try {
            json = mapper.write(clientDetails.getAdditionalInformation());
        }
        catch (Exception e) {
            logger.warn("Could not serialize additional information: " + clientDetails, e);
        }
        oAuth2ClientDetails.setResourceIds(clientDetails.getResourceIds() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
                .getResourceIds()) : null);
        oAuth2ClientDetails.setScope(clientDetails.getScope() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
                .getScope()) : null);
        oAuth2ClientDetails.setAuthorizedGrantTypes(clientDetails.getAuthorizedGrantTypes() != null ? StringUtils
                .collectionToCommaDelimitedString(clientDetails.getAuthorizedGrantTypes()) : null);
        oAuth2ClientDetails.setWebServerRedirectUri(clientDetails.getRegisteredRedirectUri() != null ? StringUtils
                .collectionToCommaDelimitedString(clientDetails.getRegisteredRedirectUri()) : null);
        oAuth2ClientDetails.setAuthorities(clientDetails.getAuthorities() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
                .getAuthorities()) : null);
        oAuth2ClientDetails.setAccessTokenValidity(clientDetails.getAccessTokenValiditySeconds());
        oAuth2ClientDetails.setRefreshTokenValidity(clientDetails.getRefreshTokenValiditySeconds());
        oAuth2ClientDetails.setAdditionalInformation(json);
        oAuth2ClientDetails.setAutoApprove(getAutoApproveScopes(clientDetails));
        return oAuth2ClientDetails;
    }
    private OAuth2ClientDetails getOauth2ClientDetailsForCreate(ClientDetails clientDetails){
        OAuth2ClientDetails oAuth2ClientDetails = new OAuth2ClientDetails();
        String json = null;
        try {
            json = mapper.write(clientDetails.getAdditionalInformation());
        }
        catch (Exception e) {
            logger.warn("Could not serialize additional information: " + clientDetails, e);
        }
        oAuth2ClientDetails.setClientSecret(clientDetails.getClientSecret());
        oAuth2ClientDetails.setResourceIds(clientDetails.getResourceIds() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
                .getResourceIds()) : null);
        oAuth2ClientDetails.setScope(clientDetails.getScope() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
                .getScope()) : null);
        oAuth2ClientDetails.setAuthorizedGrantTypes(clientDetails.getAuthorizedGrantTypes() != null ? StringUtils
                .collectionToCommaDelimitedString(clientDetails.getAuthorizedGrantTypes()) : null);
        oAuth2ClientDetails.setWebServerRedirectUri(clientDetails.getRegisteredRedirectUri() != null ? StringUtils
                .collectionToCommaDelimitedString(clientDetails.getRegisteredRedirectUri()) : null);
        oAuth2ClientDetails.setAuthorities(clientDetails.getAuthorities() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails
                .getAuthorities()) : null);
        oAuth2ClientDetails.setAccessTokenValidity(clientDetails.getAccessTokenValiditySeconds());
        oAuth2ClientDetails.setRefreshTokenValidity(clientDetails.getRefreshTokenValiditySeconds());
        oAuth2ClientDetails.setAdditionalInformation(json);
        oAuth2ClientDetails.setAutoApprove(getAutoApproveScopes(clientDetails));

        return oAuth2ClientDetails;
    }
    private String getAutoApproveScopes(ClientDetails clientDetails) {
        if (clientDetails.isAutoApprove("true")) {
            return "true"; // all scopes autoapproved
        }
        Set<String> scopes = new HashSet<String>();
        for (String scope : clientDetails.getScope()) {
            if (clientDetails.isAutoApprove(scope)) {
                scopes.add(scope);
            }
        }
        return StringUtils.collectionToCommaDelimitedString(scopes);
    }

    interface JsonMapper {
        String write(Object input) throws Exception;

        <T> T read(String input, Class<T> type) throws Exception;
    }

    private static JsonMapper createJsonMapper() {
        if (ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", null)) {
            return new JacksonMapper();
        }
        else if (ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", null)) {
            return new Jackson2Mapper();
        }
        return new NotSupportedJsonMapper();
    }

    private static class JacksonMapper implements JsonMapper {
        private org.codehaus.jackson.map.ObjectMapper mapper = new org.codehaus.jackson.map.ObjectMapper();

        @Override
        public String write(Object input) throws Exception {
            return mapper.writeValueAsString(input);
        }

        @Override
        public <T> T read(String input, Class<T> type) throws Exception {
            return mapper.readValue(input, type);
        }
    }

    private static class Jackson2Mapper implements JsonMapper {
        private com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();

        @Override
        public String write(Object input) throws Exception {
            return mapper.writeValueAsString(input);
        }

        @Override
        public <T> T read(String input, Class<T> type) throws Exception {
            return mapper.readValue(input, type);
        }
    }

    private static class NotSupportedJsonMapper implements JsonMapper {
        @Override
        public String write(Object input) throws Exception {
            throw new UnsupportedOperationException(
                    "Neither Jackson 1 nor 2 is available so JSON conversion cannot be done");
        }

        @Override
        public <T> T read(String input, Class<T> type) throws Exception {
            throw new UnsupportedOperationException(
                    "Neither Jackson 1 nor 2 is available so JSON conversion cannot be done");
        }
    }
}
